package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishOverViewVO;
import com.sky.vo.DishVO;
import com.sky.vo.SetmealOverViewVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl implements DishService {

    private static final Logger log = LoggerFactory.getLogger(DishServiceImpl.class);
    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    /**
     * 新增菜品
     *
     * @param dishDTO
     */
    @Override
    @Transactional
    public void saveWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        // 对象拷贝,获取菜品对象和口味数据
        BeanUtils.copyProperties(dishDTO, dish);
        List<DishFlavor> flavors = dishDTO.getFlavors();
        // 插入菜品数据
        dishMapper.insert(dish);

        // 判断是否存在口味数据
        if (flavors != null && !flavors.isEmpty()){
            // 去除口味数据中的无效数据
            flavors = flavors.stream()
                    .filter(f -> f.getValue() != null && !"[]".equals(f.getValue()))
                    .filter(f -> f.getName() != null && !f.getName().isEmpty())
                    .collect(Collectors.toList());
            // 插入新的菜品口味数据
            dishFlavorMapper.insertBatch(flavors, dish.getId());
        }

    }

    /**
     * 菜品分页查询
     *
     * @param dishPageQuery
     * @return
     */
    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQuery) {
        // 判断分页数据是否为空,为空则设置默认值 第一页 五条数据
        if (dishPageQuery.getPage() == 0) {
            dishPageQuery.setPage(1);
        }
        if (dishPageQuery.getPageSize() == 0) {
            dishPageQuery.setPageSize(5);
        }

        // 开启分页查询
        PageHelper.startPage(dishPageQuery.getPage(), dishPageQuery.getPageSize());
        Page<DishVO> dish = dishMapper.selectPage(dishPageQuery);
        return new PageResult(dish.getTotal(), dish.getResult());
    }

    /**
     * 批量删除菜品
     *
     * @param ids
     */
    @Override
    @Transactional
    public void deleteByIds(List<Long> ids) {
        // 判断要删除的菜品中是否包含起售中的菜品
        List<Dish> dishList = dishMapper.selectByIds(ids);
        log.info("要删除的菜品数据:{}", dishList);
        for (Dish dish : dishList) {
            if (Objects.equals(dish.getStatus(), StatusConstant.ENABLE)) {
                throw new DeletionNotAllowedException(MessageConstant.SETMEAL_ON_SALE);
            }
        }
        // 判断要删除的菜品中是否包含在套餐中的菜品
        List<SetmealDish> setmealDishList = setmealDishMapper.selectSetmealByDishIds(ids);
        log.info("要删除的菜品数据:{}", setmealDishList);
        if (setmealDishList != null && !setmealDishList.isEmpty()) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        // 删除菜品的口味数据
        dishFlavorMapper.deleteByIds(ids);
        // 删除菜品
        dishMapper.deleteByIds(ids);
    }

    /**
     * 根据id查询菜品
     *
     * @param id
     * @return
     */
    @Override
    public DishVO getByIdWithFlavor(Long id) {
        // 根据id查询菜品
        List<Dish> dishList = dishMapper.selectByIds(Collections.singletonList(id));
        // 判断菜品是否为空,如果为空返回null
        if (dishList == null || dishList.isEmpty()) {
            return null;
        }
        // 根据id查询菜品口味
        List<DishFlavor> flavors = dishFlavorMapper.selectById(id);
        // 组装数据
        DishVO dishVO = new DishVO();
        Dish dish = dishList.get(0);
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(flavors);
        return dishVO;

    }

    /**
     * 修改菜品
     *
     * @param dishDTO
     */
    @Override
    @Transactional
    public void updateWithFlavor(DishDTO dishDTO) {
        // 获取菜品对象和口味数据
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        List<DishFlavor> flavors = dishDTO.getFlavors();
        // 修改菜品数据
        dishMapper.update(dish);
        // 删除旧的菜品口味数据
        dishFlavorMapper.deleteByIds(Collections.singletonList(dish.getId()));
        // 判断是否存在口味数据
        if (flavors != null && !flavors.isEmpty()){
            // 去除口味数据中的无效数据
            flavors = flavors.stream()
                    .filter(f -> f.getValue() != null && !"[]".equals(f.getValue()))
                    .filter(f -> f.getName() != null && !f.getName().isEmpty())
                    .collect(Collectors.toList());
            // 插入新的菜品口味数据
            dishFlavorMapper.insertBatch(flavors, dish.getId());
        }
    }

    /**
     * 启用停售菜品
     * @param status
     * @param id
     */
    @Override
    public void startOrStop(Integer status, Long id) {
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .build();
        dishMapper.update(dish);
    }

    /**
     * 根据分类id查询菜品
     * @param categoryId
     * @return
     */
    @Override
    public List<Dish> list(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .build();
        return dishMapper.selectDish(dish);
    }


    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    @Override
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.selectDish(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.selectById(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }

}
